<script setup lang="ts">
import { Button, CellGroup, Dialog, Field, showFailToast, showSuccessToast } from 'vant'
import { ContactApi, ContactModelWithIsConsumer } from '~/api/ContactApi'
// import { OrderApi } from '~/api/OrderApi'
import { Common } from '~/common'
import ContactAvatar from '~/components/contact/ContactAvatar.vue'
import { ContactModel, OrderModel } from '~/model'

interface ContactWithAlias extends ContactModelWithIsConsumer {
  alias: string
}
// interface ContactGroup {
//   groupName: string
//   contacts: ContactWithAlias[]
// }
const router = useRouter()
// const allOrders = ref([] as OrderModel[])
const allContacts = ref([] as ContactWithAlias[])
const showMenu = ref(false)

const activeIndex = ref(-1)
const nameFilterInput = useSessionStorage('contact-name-filter', '')
const nameFilterInputEl = ref(null as any)

const addContactDialogVisible = ref(false)
const newContact = reactive({
  name: '',
  phone: '',
})

// type MyFilterSorter =
interface MyFilter {
  title: string
  icon: string
  filter: (c: ContactWithAlias) => boolean
  sorter?: ((a: ContactWithAlias, b: ContactWithAlias) => number)
}
const filters = [
  {
    title: '联系人',
    icon: 'user',
    filter: _ => true,
    sorter: (a, b) => {
      return a.name.localeCompare(b.name)
    },
  },
  {
    title: '用户',
    icon: 'consumer',
    filter: (x) => {
      return x.is_consumer
    },
    sorter: undefined,
  },
] as MyFilter[]

const activeFilterIndex = useLocalStorage('contact-filter', 1)

const _contactFiltered = computed(() => {
  const f = filters[activeFilterIndex.value]
  let x = allContacts.value.filter(f.filter)
  if (nameFilterInput.value) {
    x = x.filter(x => x.alias.includes(nameFilterInput.value))
  }
  if (f.sorter) {
    x.sort(f.sorter)
  }
  return x
})

const contactFiltered = computed(() => {
  if (nameFilterInput.value) {
    return _contactFiltered.value.filter(x => x.alias.includes(nameFilterInput.value))
  }
  return _contactFiltered.value
})

onMounted(async () => {
  const res = await ContactApi.getWithIsConsumer()

  // gening alias
  res.forEach((c) => {
    const _c: ContactWithAlias = c as any
    _c.alias = Common.genAlias(c)
    allContacts.value.push(_c)
  })

  // grouping
  // allContacts.value.forEach((c) => {
  //   let gpName = ''
  //   if (c.alias[0].match(/[a-z]/)) {
  //     gpName = c.alias[0]
  //   }
  //   else {
  //     gpName = '*'
  //   }
  //   const g = groups.value.find(x => x.groupName === gpName)
  //   if (!g) {
  //     groups.value.push({
  //       groupName: gpName,
  //       contacts: [c],
  //     })
  //   }
  //   else {
  //     g.contacts.push(c)
  //   }
  // })
  // groups.value.sort((a, b) => a.groupName.localeCompare(b.groupName))
})

function handleAdd() {
  newContact.name = ''
  addContactDialogVisible.value = true
}

async function addContact() {
  const _newContact = new ContactModel()
  _newContact.name = newContact.name
  _newContact.phone = newContact.phone

  if (!newContact.name) {
    showFailToast('请输入联系人姓名')
    return
  }
  if (!newContact.phone) {
    showFailToast('请输入联系人电话')
    return
  }

  const success = await ContactApi.add(_newContact)
  if (success) {
    addContactDialogVisible.value = false
    showSuccessToast('保存成功')
    setTimeout(() => {
      window.location.reload()
    }, 1000)
  }
  else {
    showFailToast('保存失败，请联系管理员')
  }
}

function detail(id: number) {
  router.push(`/contacts/detail?id=${id}`)
}

async function onAddBatch() {
  router.push('/contacts/add_batch')
}
</script>

<template>
  <div h-full w-full of-auto p4>
    <div mb flex items-center>
      <LxEntry
        v-for="(item, index) in filters" :key="index"
        :icon="item.icon"
        :title="item.title"
        :action="() => activeFilterIndex = index"
        :grid="5"
        :style="{
          border: `3px solid ${activeFilterIndex === index ? 'royalblue' : 'transparent'}`,
          borderRadius: '13px',
          marginBottom: '0px',
        }"
      />
      <img
        src="/icons/menu.png"
        ml-auto h6 w6
        @click="() => showMenu = true"
      >
    </div>
    <div h-full w-full of-auto>
      <Field
        ref="nameFilterInputEl"
        v-model="nameFilterInput"
        placeholder="搜索: 姓名，手机号"
        mb2 h-12 of-hidden b-rd border-none
      />

      <div v-for="(item, index) in contactFiltered" :key="index" h-16 flex items-center lh-16 class="consumer-list-item" :class="{ active: index === activeIndex }" @click="detail(item.id)">
        <ContactAvatar mr2 :size="12" :can-click="false" :can-unload="false" :contact="item" />
        <div>
          {{ item.name }}
        </div>
      </div>
    </div>

    <Dialog
      v-model:show="addContactDialogVisible"
      title="新建用户"
      :show-confirm-button="false"
    >
    <!-- :show-cancel-button="true"
      @confirm="addContact" -->
      <CellGroup>
        <Field
          v-model="newContact.name"
          label="姓名/单位名称"
          placeholder="请填写"
        />
        <Field
          v-model="newContact.phone"
          label="电话号码"
          placeholder="请填写"
        />
      </CellGroup>
      <div flex>
        <Button flex-1 type="primary" @click="addContact">确认</Button>
        <Button flex-1 @click="addContactDialogVisible=false">取消</Button>
      </div>
    </Dialog>

    <LxPop v-model="showMenu">
      <div flex>
        <LxEntry
          icon="add-user"
          title="新建"
          :action="handleAdd"
          :grid="3"
        />
        <LxEntry
          icon="add-users"
          title="批量导入"
          :action="onAddBatch"
          :grid="3"
        />
        <LxEntry
          icon="downloads"
          title="导出到本地"
          :action="() => {}"
          :grid="3"
        />
      </div>
    </LxPop>
  </div>
</template>

<route lang="yaml">
meta:
  title: 联系人
</route>
